// 导入数据库连接
require("./database/SqlConnection");
// 导入全局文件
let globalFile = require("./util/GlobalFile");

let express = require('express');
let app = express();
// 引入 events 模块
let events = require('events');
// 创建 eventEmitter 对象
let eventEmitter = new events.EventEmitter();
let fs = require("fs");
const RestResult = require("./util/RestResult");

let apiMap = new Map();

/**
 * 加载单独的controller
 * @param filePath 文件名
 */
function loadOneController(filePath) {
    // // 获取文件名
    // let name = fileName.split(".")[0];
    // // 获取文件后缀名
    // let suffix = fileName.split(".")[1];

    // // 如果是js文件与结尾是Controller
    // if (suffix === "js" && name.endsWith("Controller")) {
    //
    //     // 是否成功导入controller
    //     let isImport = false;
    //     let controller = null;
    //     try {
    //         controller = require("./controller/" + name);
    //         // 如果已经引入了controller，就删除重新引入
    //         delete require.cache[require.resolve("./controller/" + name)];
    //         isImport = true;
    //     } catch (e) {
    //         isImport = false;
    //     }
    //
    //     if (!isImport) {
    //         // 文件有错误
    //         console.error("controller文件有错误:" + name);
    //         return;
    //     }
    //
    //     // uri前缀
    //     let prefix = name.replace("Controller", "");
    //     // 首字母小写
    //     prefix = prefix.charAt(0).toLowerCase() + prefix.slice(1);
    //     // 获取其中所有方法
    //     let methods = Object.getOwnPropertyNames(controller);
    //     for (let j = 0; j < methods.length; j++) {
    //         let method = methods[j];
    //         pathMap.set("/" + prefix + "/" + method,controller[method]);
    //     }
    //     // 获取所有"/"+prefix+"/"开头的uri，并监听对应的方法是否已经不存在
    //     let keys = pathMap.keys();
    //     let keysArray = Array.from(keys);
    //     for (let i = 0; i < keysArray.length; i++) {
    //         if (keysArray[i].startsWith("/" + prefix + "/")) {
    //             let method = keysArray[i].replace("/" + prefix + "/", "");
    //             if (!methods.includes(method)) {
    //                 pathMap.delete(keysArray[i]);
    //             }
    //         }
    //     }
    //
    // }

    // 是否成功导入controller
    let isImport = false;
    let controller = null;
    try {
        controller = require(`./${filePath}`);
        // 如果已经引入了controller，就删除重新引入
        delete require.cache[require.resolve(`./${filePath}`)];
        isImport = true;
    } catch (e) {
        isImport = false;
    }
    // 如果文件有错误
    if (!isImport) {
        console.error("controller文件有错误:" + filePath);
        return;
    }
    // 获取文件名
    let name = filePath.split(".")[0];
    // 根据/和\\分割
    let nameArr = name.split(/[\/\\]/);
    // 取最后一个
    name = nameArr[nameArr.length - 1];
    // uri前缀
    name = name.replace("api_", "");
    // 获取其中所有方法
    let methods = Object.getOwnPropertyNames(controller);
    for (let j = 0; j < methods.length; j++) {
        let method = methods[j];
        // 只有api_开头的函数才能被调用
        if (method.startsWith("api_")) {
            let methodNames = method.substring(4);
            apiMap.set("/" + name + "/" + methodNames, controller[method]);
        }
    }
    // 查询是否对应的uri，监听对应的函数是否已经不存在
    let keys = apiMap.keys();
    let keysArray = Array.from(keys);
    for (let i = 0; i < keysArray.length; i++) {
        if (keysArray[i].startsWith("/" + name + "/")) {
            let method = keysArray[i].replace("/" + name + "/", "");
            if (!methods.includes("api_"+method)) {
                apiMap.delete(keysArray[i]);
            }
        }
    }
}



/**
 * 加载controller
 */
let loadController = () => {
    // 获取controller下所有文件
    let files = globalFile.getApiFiles();

    for (let i = 0; i < files.length; i++) {
        loadOneController(files[i]);
    }
    setTimeout(()=>{
        readableApiMap();
    },2000);
}

loadController();

// 监听所有文件变化
fs.watch(globalFile.rootPath, {recursive: true}, (eventType, filename) => {
    if (filename.indexOf("api_")!==-1 && filename.endsWith(".js")) {
        console.log(`文件发生变化:${filename}`);
        // 重新加载controller
        loadOneController(filename);
        readableApiMap();
        return;
    }
});

/**
 * 处理请求
 */
let handleRequest = async (request, response) => {
    let path = request.path;
    let inSend = apiMap.get(path);
    if (inSend == null) {
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        response.statusCode = 404;
        response.send("404 NOT PAGE");
        return;
    }

    // UTF-8编码，application/json
    response.setHeader("Content-Type", "application/json;charset=utf-8");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.statusCode = 200;
    response.statusMessage = "OK";
    // 获取所有参数
    let requestParam = request.query || {};

    let body = '';
    request.on('data', chunk => {
        body += chunk.toString();
    });

    await new Promise((resolve, reject) => {
        request.on('end', () => {
            resolve();
        })
    });


    let bodyJson = {};
    if(body){
        bodyJson=JSON.parse(body);
    }
    for (let key in bodyJson) {
        requestParam[key] = bodyJson[key];
    }

    // let result = inSend(requestParam, response);
    try {
        result = inSend(requestParam);
    } catch (e) {
        console.error(e);
        response.send(JSON.stringify(RestResult.error("error", "系统错误")));
        return;
    }

    if (result instanceof Promise) {
        result.then((data) => {
            response.send(JSON.stringify(data));
        }).catch((err) => {
            console.error(err);
            response.send(JSON.stringify(RestResult.error("error", "系统错误")));
        });
        return;
    }
    response.send(JSON.stringify(result));


}


app.get('/**', (request, response) => {
    handleRequest(request, response);
});

app.post('/**', (request, response) => {
    handleRequest(request, response);
});


let server = app.listen(8081, function () {
    let host = server.address().address
    let port = server.address().port
    console.log("应用实例，访问地址为 http://%s:%s", host, port)
})

let readableApiMap = function () {
    let keys = apiMap.keys();
    let keysArray = Array.from(keys);
    let str = "";
    for (let i = 0; i < keysArray.length; i++) {
        // console.log(keysArray[i]);
        str += (i-(-1))+":\t"+keysArray[i] + "\n";
    }
    console.log("当前API列表：\n" + str);
}